import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fishing/providers/version_provider.dart';
import 'package:fishing/models/app_version.dart';

class VersionUpdateDialog extends StatelessWidget {
  final CheckUpdateResponse updateResponse;
  final VoidCallback? onCancel;

  const VersionUpdateDialog({
    super.key,
    required this.updateResponse,
    this.onCancel,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<VersionProvider>(
      builder: (context, versionProvider, child) {
        final latestVersion = updateResponse.latestVersion!;
        final isDownloading = versionProvider.isDownloading;
        final downloadProgress = versionProvider.downloadProgress;
        final hasDownloadedFile = versionProvider.hasDownloadedFile;
        
        return PopScope(
          canPop: !updateResponse.forceUpdate,
          child: AlertDialog(
            title: Row(
              children: [
                Icon(
                  Icons.system_update,
                  color: updateResponse.forceUpdate ? Colors.red : Colors.blue,
                ),
                const SizedBox(width: 8),
                Text(
                  updateResponse.forceUpdate ? '强制更新' : '发现新版本',
                  style: TextStyle(
                    color: updateResponse.forceUpdate ? Colors.red : Colors.blue,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 版本信息
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 当前版本
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '当前版本',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.grey[700],
                            ),
                          ),
                          Text(
                            versionProvider.currentVersionInfo?['version'] ?? '未知',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      // 最新版本
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '最新版本',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.grey[700],
                            ),
                          ),
                          Text(
                            latestVersion.versionName,
                            style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.blue,
                            ),
                          ),
                        ],
                      ),
                      if (latestVersion.fileSize != null) ...[
                        const SizedBox(height: 4),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '安装包大小',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[600],
                              ),
                            ),
                            Text(
                              _formatFileSize(latestVersion.fileSize!),
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
                
                // 更新说明
                if (latestVersion.updateDescription != null) ...[
                  const SizedBox(height: 16),
                  Text(
                    '更新内容',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[700],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey[300]!),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      latestVersion.updateDescription!,
                      style: const TextStyle(fontSize: 14),
                    ),
                  ),
                ],

                // 文件状态提示
                if (hasDownloadedFile && !isDownloading) ...[
                  const SizedBox(height: 16),
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.green[50],
                      border: Border.all(color: Colors.green[200]!),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.check_circle, color: Colors.green[600], size: 16),
                        const SizedBox(width: 8),
                        const Expanded(
                          child: Text(
                            '安装包已下载完成，可直接安装',
                            style: TextStyle(
                              color: Colors.green,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],

                // 下载进度
                if (isDownloading) ...[
                  const SizedBox(height: 16),
                  Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text('下载进度'),
                          Text('${(downloadProgress * 100).toInt()}%'),
                        ],
                      ),
                      const SizedBox(height: 8),
                      LinearProgressIndicator(
                        value: downloadProgress,
                        backgroundColor: Colors.grey[300],
                        valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
                      ),
                    ],
                  ),
                ],

                // 错误信息
                if (versionProvider.errorMessage != null) ...[
                  const SizedBox(height: 16),
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.red[50],
                      border: Border.all(color: Colors.red[200]!),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.error, color: Colors.red[600], size: 16),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            versionProvider.errorMessage!,
                            style: TextStyle(
                              color: Colors.red[600],
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
            actions: [
              // 取消/跳过按钮
              if (!updateResponse.forceUpdate && !versionProvider.isDownloading)
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    onCancel?.call();
                  },
                  child: const Text('取消'),
                ),
              
              // 跳过此版本按钮
              if (!updateResponse.forceUpdate && !versionProvider.isDownloading)
                TextButton(
                  onPressed: () {
                    versionProvider.skipCurrentVersion();
                    Navigator.of(context).pop();
                  },
                  child: const Text('跳过此版本'),
                ),

              // 立即更新/安装按钮
              if (!versionProvider.isDownloading)
                ElevatedButton(
                  onPressed: versionProvider.isChecking 
                      ? null 
                      : () {
                          if (hasDownloadedFile) {
                            // 如果已有下载文件，直接安装
                            versionProvider.installDownloadedApk();
                          } else {
                            // 否则开始下载
                            versionProvider.startDownload();
                          }
                        },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: hasDownloadedFile ? Colors.green : Colors.blue,
                  ),
                  child: versionProvider.isChecking
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : Text(hasDownloadedFile ? '立即安装' : '立即更新'),
                ),
            ],
          ),
        );
      },
    );
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '${bytes}B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)}KB';
    if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
  }

  /// 显示更新对话框
  static Future<void> show(
    BuildContext context,
    CheckUpdateResponse updateResponse, {
    VoidCallback? onCancel,
  }) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: !updateResponse.forceUpdate,
      builder: (context) => VersionUpdateDialog(
        updateResponse: updateResponse,
        onCancel: onCancel,
      ),
    );
  }
}